/**
    Copyright (C) 2012 Guido Ludwig

    This file is part of JATT.
	http://code.google.com/p/jatt/

    JATT is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.guidoludwig.jatt.chain.commands;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.guidoludwig.jatt.JATT;
import de.guidoludwig.jatt.chain.JATTContext;
import de.guidoludwig.jatt.chain.commands.config.SelectOptimizedImageConfig;
import de.guidoludwig.jatt.util.ArtworkFilenameFilter;
import de.guidoludwig.jatt.util.JATTCompressor;
import de.guidoludwig.jatt.util.ImageInfo;
import de.guidoludwig.jatt.util.JATTUtil;

/**
 * @author Guido Ludwig
 */
public class SelectOptimizedImageCommand extends
		JATTCommand<SelectOptimizedImageConfig> {

	@Override
	protected boolean execute0(JATTContext context) {
		List<ImageInfo> compressed;
		try {
			compressed = getImageCandidates(context);
		} catch (IOException e1) {
			JATT.error(e1);
			return false;
		}
		if (compressed == null || compressed.isEmpty()) {
			return false;
		}
		Collections.sort(compressed, getConfig().getComparator());
		
		ImageInfo best = compressed.get(0);
		if (isFolderImage(context, best)) {
			JATT.debug("Folder Image is already best available");
			return false;
		}
		try {
			File folderImage = copyToFolderImage(context, best, getConfig().isBackup());
			context.setFolderImage(folderImage);
			JATT.debug("Copied to folder image done");
		} catch (IOException e) {
			JATT.error(e);
		}
		return false;
	}
	
	private List<ImageInfo> getImageCandidates(JATTContext context) throws IOException {
		JATTCompressor compressor = new JATTCompressor(getConfig().getWidth(), getConfig().getSize());
		List<ImageInfo> candidates = new ArrayList<ImageInfo>();
		for (ImageInfo imageInfo : context.getAllImageInfo()) {
			candidates.add(compressor.optimize(imageInfo));
		}
		return candidates;
	}


	private boolean isFolderImage(JATTContext context, ImageInfo best) {
		if (best == null || context.getFolderImageInfo() == null) {
			return false;
		}
		return best.getFile().getAbsolutePath()
				.equals(context.getFolderImageFile().getAbsolutePath());
	}

	private File copyToFolderImage(JATTContext context, ImageInfo imageInfo, boolean backup)
			throws IOException {
		String extension = imageInfo.getExtension();
		if (extension == null) {
			throw new IllegalStateException("No extension for " + imageInfo.getFile().getAbsolutePath());
		}
		String fileName = ArtworkFilenameFilter.FOLDER_PREFIX + "." + extension;
		File input = imageInfo.getFile();

		File output = new File(context.getDirectory(), fileName);
		if (backup && output.exists()) {
			String backupName = ArtworkFilenameFilter.FOLDER_PREFIX
					+ ".backup." + extension;
			File backupFile = new File(context.getDirectory(),
					backupName);
			if (backupFile.exists()) {
				JATTUtil.copyFile(output, backupFile, true);
			} else {	
				JATTUtil.copyFile(output, backupFile, true);
				context.addToAlternativeImages(backupFile);
			} 
		}
		JATTUtil.copyFile(input, output, true);
		return output;
	}

}
